extends Node2D

@onready var points:Points = get_node("/root/Board_v2/Points")
@onready var pieces:Pieces = get_node("/root/Board_v2/Pieces")
@onready var game:ChineseChess = get_node("/root/Board_v2")
@onready var animationManager:AnimationManager = get_node("/root/Board_v2/AnimationManager")
@onready var validator:ValidatorController = get_node("/root/Board_v2/ValidateController")
@onready var gameEvaluationResource:Resource = preload("res://Board/Script/game_evaluation.gd")
@onready var isIncheckResource:Resource = preload("res://Board/Script/IsInCheck.gd")

var selected_piece:PieceV2
var selected_pos:Vector2
var defult_pos:Vector2=Vector2(-1,-1)
var gameEvaluation:GameEvaluation ## 游戏局势
var isInCheck ## 将军检测

func _ready() -> void:
	gameEvaluation=gameEvaluationResource.new()
	isInCheck=isIncheckResource.new()

	GlobalSignals.ai_move_signal.connect(handle_ai_move)
	pieces.selected_piece_signal.connect(_on_select_piece)
	points.select_grid_signal.connect(_on_select_grid)

	selected_pos=defult_pos
	
func _on_select_piece(piece:PieceV2) ->void:
	if (game.current_turn==piece.side): 
		selected_piece=piece
		pieces.update_piece_signal.emit(piece,true)

func _on_select_grid(point:Point) -> void:
	if selected_piece:
		selected_pos=point.position
		handle(selected_piece,selected_pos)

@warning_ignore("unused_parameter")
func handle(select_piece:PieceV2,select_pos:Vector2) -> void:
	if !selected_piece or selected_pos==defult_pos: return
	move_target(selected_pos)
	

func move_target(pos:Vector2) -> void:
	if selected_piece.position == pos:return
	# 检查当前区域是否有本方棋子
	var findPiece:PieceV2 = pieces.find_piece(pos)
	if not findPiece or findPiece.side != selected_piece.side:
		# 检查棋子移动规则
		var from_pos=BoardCommon.pos_to_grid_pos(selected_piece.position)
		var tar_pos=BoardCommon.pos_to_grid_pos(pos)

		var isValidator:bool = validator.validate_piece(selected_piece,from_pos,tar_pos)
		if isValidator:
			# 处理移动得分逻辑
			gameEvaluation.handle_move_score(selected_piece.side,selected_piece.type,from_pos,tar_pos)
			selected_piece.position = pos
			# 检查将军状态
			isInCheck.set_validator(validator) # 移动校验
			var is_check:bool = isInCheck.check_any_check(selected_piece.side,pieces) # 检查是否叫将
			if is_check: GlobalSignals.animation_player_signal.emit("Check") # 播放动画
			if findPiece: 
				gameEvaluation._on_calculate_piece_died(findPiece.side,findPiece.type)
				## 检查被吃掉的棋子是否是将/帅
				if findPiece.type==BoardCommon.TYPE.GENERAL:
					GlobalSignals.game_status_game_over_signal.emit(selected_piece.side)
				findPiece.queue_free()
			selected_piece=null
			selected_pos=defult_pos
			var turn:BoardCommon.TURN=game.current_turn
			game.change_turn()

			if turn==BoardCommon.TURN.RED:
				handle_ai_move()

## 处理ai移动逻辑
func handle_ai_move() -> void:
	await get_tree().create_timer(1.0).timeout
	var ai_move:Dictionary = ChatAi._ai_move()
	var piece:PieceV2 = ai_move['piece'] # 棋子
	var from_grid_pos:Vector2i = ai_move['from_pos'] # 目标位置
	var tar_grid_pos:Vector2i = ai_move['to_pos'] # 目标位置

	selected_piece=piece
	selected_pos=BoardCommon.grid_pos_to_pos(from_grid_pos)
	var find_piece_pos=BoardCommon.grid_pos_to_pos(tar_grid_pos)
	var findPiece:PieceV2 = pieces.find_piece(find_piece_pos)

	##todo 需要验证棋子移动合法性

	selected_piece.position = find_piece_pos
	print("AI选择移动棋子：",piece.type,"从位置",from_grid_pos,"到位置",tar_grid_pos)
	# 处理移动得分逻辑
	gameEvaluation.handle_move_score(selected_piece.side,selected_piece.type,from_grid_pos,tar_grid_pos)
	# 检查将军状态
	isInCheck.set_validator(validator) # 移动校验
	var is_check:bool = isInCheck.check_any_check(selected_piece.side,pieces) # 检查是否叫将
	if is_check: GlobalSignals.animation_player_signal.emit("Check") # 播放动画
	if findPiece: 
		gameEvaluation._on_calculate_piece_died(findPiece.side,findPiece.type)
		## 检查被吃掉的棋子是否是将/帅
		if findPiece.type==BoardCommon.TYPE.GENERAL:
			GlobalSignals.game_status_game_over_signal.emit(selected_piece.side)
		findPiece.queue_free()
	game.change_turn()
	selected_piece=null
	selected_pos=defult_pos
